import { Component } from '@angular/core';
import { NavController, AlertController } from '@ionic/angular';
import { ShopService } from '../services/shop.service';
import * as constants from '../providers/Constants'
import { ToastService } from '../providers/toast/toast.service'
import { OrderService } from '../services/order.service';
import { Helper } from '../providers/Helper';
import { AuthService } from '../services/auth.service';
import { Storage } from '../providers/Storage';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { Utils } from '../providers/Utils';

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page {
  managementStr: string = 'Edit'
  shopcart: any = [];
  userInfoStatus: number = 0;  //0正常   1未登录 2登录购物车为空
  allPrise: number = 0;
  allNum: number = 0;
  imageUrl: string = '';
  isDelect: boolean = true;
  allCheckbox: boolean = true;
  isIOS: boolean = false;
  constructor(public alertCtrl: AlertController,
    public nav: NavController,
    private shop: ShopService,
    private order: OrderService,
    private mHelper: Helper,
    private statusBar: StatusBar,
    private toast: ToastService,
    private mAuthService: AuthService, ) {
      this.imageUrl=this.shop.getImageUrl()
    // this.statusBar.overlaysWebView(true);
    console.log('ios==', this.mHelper.isIos());
    this.isIOS = this.mHelper.isIos();
  }

  management() {
    if (this.managementStr == 'Edit') {
      this.managementStr = 'Done'
    } else {
      this.managementStr = 'Edit'
    }
  }
  onClickCheck() {
    let box = this.allCheckbox;
    for (let index = 0; index < this.shopcart.length; index++) {
      const element = this.shopcart[index];
      element.isSelect = !box
    }
    console.log('allCheckbox', this.allCheckbox);

  }
  onClickItem(item) {
    this.nav.navigateForward(['/goods-details'], {
      queryParams: {
        shopInfo: JSON.stringify(item),
      }
    });
  }
  solaImage(img){
    return Utils.imageUrl(this.imageUrl,img);
  }

  ionViewDidEnter() {
    let token = Storage.localStorage.get("userPhone");
    if (token) {
      this.query();
    }
    // this.query();
  }
  AmountOfConversion(num: number) {
    return num / 100;
  }
  query() {
    this.shop.queryShoppingCar({}).subscribe(res => {
      // 保存成功返沪上一页，否则弹出提示框
      if (res.retCode == '000000') {
        res.data.forEach(element => {
          element.isSelect = false;
          if (!element.num) {
            element.num = 1;
          }
          element.procImg = element.procImg.split(',')[0]
        });
        if (res.data.length > 0) {
          this.userInfoStatus = 2;
          this.shopcart = res.data
          this.userInfoStatus = 2;
        } else {
          this.shopcart = null;
        }
        // else {
        //   this.userInfoStatus = 2;
        // }
        this.countMoney();
        // this.procArray = res.procArray
      } else if (constants.errCode[res.retCode]) {
        if (constants.errCode[res.retCode] != '0') { this.toast.show(constants.errCode[res.retCode]); }
      } else if (res.retMsg) {
        this.toast.show(res.retMsg);
      } else {
        this.toast.show("exception service routine");
      }
    });

  }



  /**
    * 
    * @param index  第一个数组 标识
    * @param idx  第二个数组 标识
    */
  subtract(index,$event) {
    $event.stopPropagation();
    if (this.shopcart[index].num <= 0) {
      return;
    }
    this.shopcart[index].num--;
    this.countMoney();
  }

  subtract1(index,$event) {
    $event.stopPropagation();
    this.shopcart[index].num++;
    this.countMoney();
  }

  onClick() {
    // this.shopDetail.num = 1;
    let data = [];
    for (let index = 0; index < this.shopcart.length; index++) {
      const element = this.shopcart[index];
      if (element.select) {
        element.procStandards = element.size
        data.push(element);
      }
    }
    console.log(data.length);
    if (data.length > 0) {
      this.nav.navigateForward('order-create', {
        queryParams: {
          type: 1,
          procPriceId: data[0].procPriceId,
          // procPriceId:data[0].procPriceId,
          shoppingCart: 1,
          goodsInfo: JSON.stringify(data)
        }
      });
    } else {
      this.toast.show('You need specify order items');
    }


  }


  deleteOne(products_item,$event) {
    $event.stopPropagation();
    this.shop.delShoppingCar({ shoppingCarId: [products_item.shoppingCarId] }).subscribe(res => {
      // 保存成功返沪上一页，否则弹出提示框
      if (res.retCode == '000000') {
        this.query();
        // this.procArray = res.procArray
      } else if (constants.errCode[res.retCode]) {
        if (constants.errCode[res.retCode] != '0') { this.toast.show(constants.errCode[res.retCode]); }
      } else if (res.retMsg) {
        this.toast.show(res.retMsg);
      } else {
        this.toast.show("exception service routine");
      }
    });
  }


  delete(array) {
    console.log('this.allCheckbox==', this.allCheckbox);
    if (this.allCheckbox) {
      this.shop.delShoppingCar({ shoppingCarId: array }).subscribe(res => {
        // 保存成功返沪上一页，否则弹出提示框
        if (res.retCode == '000000') {
          this.query();
          // this.numAllPrice();
          // this.procArray = res.procArray
        } else if (constants.errCode[res.retCode]) {
          if (constants.errCode[res.retCode] != '0') { this.toast.show(constants.errCode[res.retCode]); }
        } else if (res.retMsg) {
          this.toast.show(res.retMsg);
        } else {
          this.toast.show("exception service routine");
        }
      });
    } else {
      this.toast.show('No items');
    }

  }
  onDel() {
    if (this.isDelect) {
      let array = [];
      for (let index = 0; index < this.shopcart.length; index++) {
        const element = this.shopcart[index];
        console.log(element);
        if (element.select) {
          array.push(element.shoppingCarId)
        }
      }
      this.delete(array);
    }
  }
  pitchAll(index, item) {
    console.log('*************************');

    // for (let idx = 0; idx < this.shopcart[index].length; idx++) {
    if (!item.select) {
      this.shopcart[index].select = true
    } else {
      this.shopcart[index].select = false
    }
    console.log(this.shopcart);

    // }
    this.countMoney(0);
  }
  countMoney(type: number = 0) {
    this.allPrise = 0;
    this.allNum = 0;
    this.shopcart.forEach(element => {
      if (type == 0) {
        if (element.select) {
          this.allNum++;
          this.allPrise = this.allPrise + element.procCashPrice * element.num;
        }
      } else {
        if (!element.select) {
          this.allNum++;
          this.allPrise = this.allPrise + element.procCashPrice * element.num;
        }
      }
    });
    // if (this.allPrise >= 1) {
    //   this.allCheckbox = true;
    // } else {
    //   this.allCheckbox = false;
    // }
  }
  pitch(index, idx, item) {
    if (!item.select) {
      this.shopcart[index].shopList[idx].select = false;
    } else {
      this.shopcart[index].shopList[idx].select = true;
    }
    this.countMoney(1);
  }
  clear() {
    this.shop.delShoppingCarAll({}).subscribe(res => {
      // 保存成功返沪上一页，否则弹出提示框
      if (res.retCode == '000000') {
        this.toast.show("Done");
        this.query();
      } else if (constants.errCode[res.retCode]) {
        if (constants.errCode[res.retCode] != '0') { this.toast.show(constants.errCode[res.retCode]); }
      } else if (res.retMsg) {
        this.toast.show(res.retMsg);
      } else {
        this.toast.show("exception service routine");
      }
    });
  }

}
